package com.n9.qqonline.sales.service;

import com.n9.qqonline.sales.product.MemoryPatentService;
import com.n9.qqonline.sales.product.Patent;
import com.n9.qqonline.sales.view.FreemarkerUtils;
import com.n9.qqonline.sales.vo.BuyMsgVo;
import com.n9.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author ice
 * @since 2019/3/19 15:44
 */
public class MsgContenUtils {
    /**
     * 带样式的消息
     * @param buyMsgVo
     * @return
     */
    public static String getStyleContent(BuyMsgVo buyMsgVo, String[] searchKeyWords) {
        String msgContent = buyMsgVo.getContent();
        msgContent = msgContent.replaceAll("\\\n", "<br/>");
        String sendNick = StringUtils.hasText(buyMsgVo.getSendNick()) ? buyMsgVo.getSendNick() : "群成员";
        buyMsgVo.setSendNick(sendNick);

        if (Objects.nonNull(searchKeyWords)) {
            for (int i = 0; i < searchKeyWords.length; i++) {
                String keyWord = searchKeyWords[i];
                if (StringUtils.hasText(keyWord)) {
                    msgContent = msgContent.replaceAll(keyWord, String.format("<a style='color:red;font-weight:bold;'>%s</a>", keyWord));
                }
            }
        }

        MemoryPatentService memoryPatentService = new MemoryPatentService();
        List<String> tags = memoryPatentService.getTags();
        for (int i = tags.size()-1; i >= 0; i--) {
            String tagKeyWord = tags.get(i);
            if (msgContent.contains(tagKeyWord)) {
                msgContent = msgContent.replaceAll(tagKeyWord, String.format("<a style='color:#CD00CD;font-weight:bold;'>%s</a>", tagKeyWord));

                List<Patent> patents = memoryPatentService.getPatentByTag(tagKeyWord);
                patents.forEach(p->{
                    if (!p.isSoldOut() && !buyMsgVo.isExistPatent(p)) {
                        buyMsgVo.getPatents().add(p);
                    }
                });
            }
        }
        buyMsgVo.setContent(msgContent);

        Map<String, Object> map = new HashMap<>(0);
        map.put("buyMsg", buyMsgVo);
        return FreemarkerUtils.render("buyMsg.ftl", map);
    }
}
